package tasks

import (
	"errors"
	"path/filepath"
	"strings"

	"torler.com/qingyue/apps/spider/internal/core/task"
	"torler.com/qingyue/common/model"
	"torler.com/qingyue/common/types"
	jfile "torler.com/qingyue/pkg/file"
)

const (
	RUNNER_LOCAL_BOOK_PROCESS = types.RunnerName("task_book_local_process")
	TASK_LOCAL_BOOK_PROCESS   = types.TaskName("本地小说分析处理任务")
)

type LocalBookProcessTask struct {
	lId string
}

func NewLocalBookProcessTask() *LocalBookProcessTask {
	return &LocalBookProcessTask{}
}

// 任务执行者预加载
func (it *LocalBookProcessTask) Preload(t *task.Task) error {
	it.lId = task.GetParam[string](t, "lbook_id")
	return nil
}

// 任务执行者的唯一名称标识用于反序列化
func (it *LocalBookProcessTask) Name() types.RunnerName {
	return RUNNER_LOCAL_BOOK_PROCESS
}

// 任务执行者
func (it *LocalBookProcessTask) Run(tsk *task.Task) error {
	db := tsk.GetCtx().DB
	var rawBook *model.RawBook
	db.Where("id=?", it.lId).Find(&rawBook)

	if rawBook == nil || rawBook.Id.IsZero() {
		return errors.New("小说不存在")
	}
	defer db.Save(rawBook)

	roots := []string{"/mnt/novel", "/mnt/ebook/"}
	var lines *[]string
	for _, root := range roots {
		extra := rawBook.GetExtraAsImportedExtra()

		path := filepath.Join(root, extra.FilePath)
		lines, _ = jfile.ReadFile(path)
		if lines != nil {
			break
		}
	}
	if lines == nil {
		rawBook.MetaState = types.MetaStateNotFound
		return errors.New("小说不存在")
	}
	err := it.processBookInfo(lines, rawBook)
	if err != nil {
		rawBook.MetaState = types.MetaStateImportedError
		return err
	}
	err = it.processBookChapters(lines, rawBook)
	if err != nil {
		rawBook.MetaState = types.MetaStateImportedError
		return err
	}
	err = it.saveChapterContent(rawBook)
	rawBook.MetaState = types.MetaStateImported
	return nil

}

// 处理小说的基本信息
func (it *LocalBookProcessTask) processBookInfo(lines *[]string, book *model.RawBook) error {
	for idx, line := range *lines {

		//只处理前50行的内容
		if idx > 50 {
			return nil
		}
		if strings.Contains(line, "书名") {
			book.BookName = strings.TrimSpace(strings.Split(line, "书名")[1])
		} else if strings.Contains(line, "作者") {
			book.Author = strings.TrimSpace(strings.Split(line, "作者")[1])
		} else if strings.Contains(line, "分类") {
			book.CategoryName = strings.TrimSpace(strings.Split(line, "分类")[1])
		} else if strings.Contains(line, "简介") {
			book.Desc = strings.TrimSpace(strings.Split(line, "简介")[1])
		}

	}
	return nil
}

// 处理小说的章节信息
func (it *LocalBookProcessTask) processBookChapters(lines *[]string, book *model.RawBook) error {

	return nil
}

// 保存章节内容到文件
func (it *LocalBookProcessTask) saveChapterContent(book *model.RawBook) error {
	return nil
}
